package netbay;

import java.io.File;
import java.io.IOException;
import java.util.Date;

public class Worker implements Runnable {

	private String fileName;
	public String cmd;

	private String attachName;
	private String ctrlName;

	FileDao fileMng = null;

	public Worker(String getFileName, String getCmd) {
		fileName = getFileName;
		cmd = getCmd;

		fileMng = new FileDao();
	}

	@Override
	public void run() {

		if (cmd.equalsIgnoreCase(WorkerManager.TCDRecvCmd)) {

			ctrlName = fileName;

			recvTCD();

		} else if (cmd.equalsIgnoreCase(WorkerManager.JPMCRecvCmd)) {

			attachName = fileName;

			recvJPMC();

		}
	}

	private void recvTCD() {


		File ctrlFile = new File(WorkerManager.TCDRecvDir + "/" + ctrlName);

		TransactionLog log = TransactionLog.convertTcdCtrlFile(ctrlFile);

		// check error task
		if (log == null) {
			WorkerManager.reportId(ctrlName, cmd);
			return;
		}

		attachName = log.getTcdAttach();

		// need to check if attach file are existed or not
		File attach = new File(WorkerManager.TCDRecvDir + "/" + attachName);
		if (attach.exists()) {

			TransactionManager manager = new TransactionManager();
			TransactionLog registeredLog = null;
			Integer id = null;

			// check if it was process before
			TransactionLog testLog = manager.findTransactionByConverId(log
					.getConverId());
			if (testLog == null) {
				id = manager.saveTransaction(log);
				registeredLog = manager.findTransactionById(id);

				// update recvTcdTime
				registeredLog.setTimeEntry(TransactionManager.recvTcdStatus);
				
				sendJPMC(registeredLog);
				
			} else {
				// report to remove flag lock because the file is duplicated
				WorkerManager.reportId(ctrlName, cmd);
				return;
			}

			// error occur while save record
			if (id == null) {
				// report to remove flag lock to wait for next time
				WorkerManager.reportId(ctrlName, cmd);
				return;
			}

		}

		// report to remove flag lock because it can't start task without
		// attach file
		WorkerManager.reportId(ctrlName, cmd);
	}

	// separate to use for resend feature
	// need to logging the resend event if use this method to resend

	private void sendJPMC(TransactionLog log) {

		File ctrlFile = new File(WorkerManager.TCDRecvDir + "/"
				+ log.getTcdCtrl());
		File attach = new File(WorkerManager.TCDRecvDir + "/"
				+ log.getTcdAttach());

		// must backup to database via blob in table archived
		TransactionManager manager = new TransactionManager();
		manager.insertArchivedToDB(ctrlFile);
		manager.insertArchivedToDB(attach);

		// update begin transfer time
		log.setTimeEntry(TransactionManager.beginSendJpmcStatus);

		// need to sftp before delete
		SFTPManager sftp = new SFTPManager();
		File srcAttachFile = new File(WorkerManager.TCDRecvDir + "/"
				+ attachName);
		File srcCtrlFile = new File(WorkerManager.TCDRecvDir + "/" + ctrlName);

		boolean attachSucceed = false;

		attachSucceed = sftp.sendSFTPFile(srcAttachFile,
				srcAttachFile.getName());

		boolean ctrlSucceed = false;

		ctrlSucceed = sftp.sendSFTPFile(srcCtrlFile, srcCtrlFile.getName());

		if (ctrlSucceed && attachSucceed) {
			// update finish send sftp
			log.setTimeEntry(TransactionManager.finSendJpmcStatus);

			// delete
			fileMng.deleteFile(srcAttachFile);
			fileMng.deleteFile(srcCtrlFile);

			// report to remove flag lock after finish
			WorkerManager.reportId(ctrlName, cmd);
		}

		// report to remove flag lock because it can't send files
		WorkerManager.reportId(ctrlName, cmd);

	}

	private void recvJPMC() {

		TransactionManager manager = new TransactionManager();

		TransactionLog registeredLog = manager
				.findTransactionByAttach(attachName);

		//use to check was it process before
		if (!manager.updateJpmcDetail(registeredLog, attachName)) {
			// error can't update JPMCDetail or this attach was processed before
			// report to unlock task and wait for next operate time
			WorkerManager.reportId(attachName, cmd);
		}
		
		sendTCD(registeredLog);

	}

	// separate to use for redownload feature
	// need to logging the redownload event if use this method to redownload

	public void sendTCD(TransactionLog log) {

		TransactionManager manager = new TransactionManager();

		// update recvJPMCTime
		log.setTimeEntry(TransactionManager.recvJpmcStatus);

		ctrlName = log.getJpmcCtrl();

		File ctrlFile = new File(WorkerManager.JPMCDesDir + "/" + ctrlName);
		log.createJpmcCtrlFile(ctrlFile);

		// need to get attachFile from sftp to temp dir before continue

		SFTPManager sftpManager = new SFTPManager();
		File tempAttachfile = new File(WorkerManager.JPMCRecvDir + "/"
				+ attachName);

		boolean attachSucceed = false;

		attachSucceed = sftpManager.getSFTPFile(attachName, tempAttachfile);

		if (attachSucceed) {

			// must backup to database via blob in table archived

			TransactionManager TransManager = new TransactionManager();
			TransManager.insertArchivedToDB(ctrlFile);
			TransManager.insertArchivedToDB(tempAttachfile);

			// copy only attach file because ctrl file was generated in the
			// destination

			File attachFileDes = new File(WorkerManager.JPMCDesDir + "/"
					+ attachName);

			boolean sendTCD = false;

			try {
				fileMng.copyFile(tempAttachfile, attachFileDes);
				sendTCD = true;
			} catch (IOException e) {
				e.printStackTrace();
			}

			if (sendTCD) {
				// update send TCD
				log.setTimeEntry(TransactionManager.sendTcdStatus);

				// delete used file

				fileMng.deleteFile(attachFileDes);

				// comment due to change requirement
				// need to delete file from SFTP
//				attachSucceed = sftpManager.removeSFTPFile(attachName);
//
//				if (!attachSucceed) {
//					System.out.println("error can't delete file on SFTP");
//				}

				// report finish job
				WorkerManager.reportId(attachName, cmd);
			}
		} else {
			// report to unlock task and wait for next operate time
			WorkerManager.reportId(attachName, cmd);
		}
	}

}
